// import styles from "./Editor.module.css";
import { Button, Form, Input, Modal, Space } from "antd";
import { toast } from "../../../../../components/Toast/Toast";
import { keywordApi, passwordApi } from "../../../../../utils/backend/server";
import {
  converter,
  EditorType,
  OptionalPasswordType,
  WithPass,
} from "../../Password/Password";
import React, { useEffect, useState } from "react";
import { updateForm as updateInput } from "../../../../../utils/utils/setInput";

export const Editor = (props: { data: EditorType; reload: () => void }) => {
  const [form, setForm] = useState<EditorType>(converter(props.data));

  useEffect(() => {
    setForm(converter(props.data));
  }, [props.data]);

  const check = (data: EditorType) => {
    const item = data.pair.find(
      (val) => val.account === "" || val.password === ""
    );
    if (item) {
      toast(`please check ${item.account === "" ? "account" : "password"}`);
      return false;
    }
    return true;
  };
  // const handleOk = async () => {
  //   if (!check(form)) return;
  //   try {
  //     // await passwordApi[
  //     //   props.data.isEdit ? "updatePassword" : "createPassword"
  //     // ](form);
  //     const res = await passwordApi.updatePassword(
  //       String(form.id || ""),
  //       form.pair
  //     );
  //     props.reload();
  //     handleCancel();
  //   } catch (error) {
  //     // handleLoginError(error as AxiosError);
  //   }
  // };
  const handleCancel = () => {
    setForm({
      show: false,
      // url: "",
      pair: [
        {
          account: "",
          password: "",
          memo: "",
          type: "password",
        },
      ],
      memo: "",
      isEdit: false,
    });
  };

  const addPair = () => {
    setForm((e) => ({
      ...e,
      pair: [
        ...e.pair,
        {
          password: "",
          account: "",
          memo: "",
          type: "password",
        },
      ],
    }));
  };

  const updateForm = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => updateInput(e, setForm);

  const removePair = (index: number) => {
    if (form.pair.length === 1) return toast("at least leave one pair!");
    setForm((e) => ({
      ...e,
      pair: (e.pair as unknown as WithPass[]).filter(
        (val, seq: number) => seq !== index
      ),
    }));
  };

  const visibility = (type: "password" | "text", index: number) => {
    setForm((val) => ({
      ...val,
      pair: val.pair.map((e, seq) => ({
        ...e,
        type: seq === index ? type : e.type,
      })),
    }));
  };

  return (
    <Modal
      open={form.show}
      onCancel={handleCancel}
      title={form.isEdit ? "edit" : "add"}
      destroyOnClose
      footer={
        <Space>
          <Button danger onClick={addPair}>
            add
          </Button>
          <Button
            type="primary"
            onClick={() => {
              // handleOk
            }}
          >
            confirm
          </Button>
        </Space>
      }
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={() => {}}
        onFinishFailed={() => {}}
        autoComplete="off"
      >
        {/* className={styles.pair} */}
        <div>
          {form.pair.map((val, index) => (
            <div key={"pair" + index}>
              <Form.Item<OptionalPasswordType>
                label="account"
                rules={[
                  { required: true, message: "Please input your account!" },
                ]}
                initialValue={val.account}
              >
                <Space.Compact style={{ width: "100%" }}>
                  <Input
                    value={val.account}
                    name={`['pair']['${index}']['account']`}
                    onChange={updateForm}
                  />
                  <Button
                    type="primary"
                    danger
                    onClick={() => removePair(index)}
                  >
                    -
                  </Button>
                </Space.Compact>
              </Form.Item>
              <Form.Item<OptionalPasswordType>
                label="password"
                rules={[
                  { required: true, message: "Please input your password!" },
                ]}
                initialValue={val.password}
              >
                <Space.Compact style={{ width: "100%" }}>
                  <Input
                    value={val.password}
                    name={`['pair']['${index}']['password']`}
                    onChange={updateForm}
                    type={val.type}
                  />
                  <>
                    <Button
                      type="primary"
                      onClick={() =>
                        visibility(
                          val.type === "password" ? "text" : "password",
                          index
                        )
                      }
                    >
                      {val.type === "password" ? "show" : "hide"}
                    </Button>
                    {form.pair.length - 1 === index ? (
                      <Button type="primary" onClick={addPair}>
                        +
                      </Button>
                    ) : (
                      <></>
                    )}
                  </>
                </Space.Compact>
              </Form.Item>
            </div>
          ))}
        </div>
      </Form>
    </Modal>
  );
};
